package com.sgam.mf.dao;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;

public abstract class GenericDAOImpl<T> implements GenericDAO<T> {

	@Autowired
	SessionFactory sessionFactory;

	private Class<T> clazz;

	public final void setClazz(Class<T> clazzToSet) {
		this.clazz = clazzToSet;
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public GenericDAOImpl() {
		Type t = getClass().getGenericSuperclass();
		ParameterizedType pt = (ParameterizedType) t;
		clazz = (Class) pt.getActualTypeArguments()[0];
	}

	@SuppressWarnings("unchecked")
	public T get(Integer id) {
		T result = (T) getCurrentSession().get(clazz, id);
		return result;
	}

	@SuppressWarnings("unchecked")
	public T load(Integer id) {
		T result = (T) getCurrentSession().load(clazz, id);
		return result;
	}

	@SuppressWarnings("unchecked")
	public T update(T entity) {

		return (T)getCurrentSession().merge(entity);
	}
	
	public void delete(T entity) {
		getCurrentSession().delete(entity);
	}

	@SuppressWarnings("unchecked")
	public List<T> list() {
		List<T> result = getCurrentSession().createQuery(
				"from " + clazz.getName() +" order by id" ).list();///02.12.2014 order by condition added
		return result;
	}

	public List<T> filter(Map<String, String[]> filtersMap) {
		return list();
	}

	public void deleteById(Integer id) {
		getCurrentSession()
				.createQuery(
						"delete from " + clazz.getName() + " where id = :pid")
				.setParameter("pid", id).executeUpdate();
	}

	protected final Session getCurrentSession() {
		return sessionFactory.getCurrentSession();
	}
}
